package cn.lili.modules.promotion.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SecurityEnum;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.promotion.entity.dos.Ticket;
import cn.lili.modules.promotion.entity.dos.TicketPoll;
import cn.lili.modules.promotion.entity.dos.TicketPollRecord;
import cn.lili.modules.promotion.mapper.TicketPollMapper;
import cn.lili.modules.promotion.mapper.TicketPollRecordMapper;
import cn.lili.modules.promotion.service.TicketPollRecordService;
import cn.lili.modules.promotion.service.TicketPollService;
import cn.lili.modules.statistics.entity.enums.SearchTypeEnum;
import cn.lili.modules.statistics.util.StatisticsDateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class TicketPollServiceImpl extends ServiceImpl<TicketPollMapper, TicketPoll>
        implements TicketPollService {

    private final RedissonClient redissonClient;

    @Resource
    private TicketPollRecordMapper ticketPollRecordMapper;

    @Override
    public List<TicketPoll> getList(String pollName, HttpServletRequest request) {
        LambdaQueryWrapper<TicketPoll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(pollName) && !"null".equals(pollName), TicketPoll::getPollName, pollName);
        List<TicketPoll> ticketPollList = this.list(queryWrapper);
        String accessToken = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue());
        if (!ticketPollList.isEmpty() && StringUtils.isNotEmpty(accessToken)) {
            ticketPollList.forEach(ticketPoll -> {
                TicketPollRecord ticketPollRecord = getByPollId(ticketPoll.getId());
                ticketPoll.setIsVote(null != ticketPollRecord);
            });
        }
        return ticketPollList;
    }

    /**
     * 添加嘉宾
     * @param ticketPoll
     */
    @Override
    public void addTicketPoll (TicketPoll ticketPoll) {
        if (null == ticketPoll || StringUtils.isEmpty(ticketPoll.getPollName())
                || StringUtils.isEmpty(ticketPoll.getPicture())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        ticketPoll.setId(SnowFlake.getIdStr());
        ticketPoll.setTicketNumber(0);
        this.save(ticketPoll);
    }

    /**
     * 添加票数
     * @param id
     * @param number
     */
    @Override
    public void addPoll (String id, Integer number) {
        RLock rLock = redissonClient.getLock("addPoll_" + id);
        try {
            boolean b = rLock.tryLock(1000, 2000, TimeUnit.MILLISECONDS);
            if (b) {
                TicketPoll ticketPoll = this.getById(id);
                if (null == ticketPoll) {
                    throw new ServiceException("投票嘉宾不存在");
                }
                ticketPoll.setTicketNumber(ticketPoll.getTicketNumber() + number);
                this.updateById(ticketPoll);
            }
        }catch (Exception e) {
            throw new ServiceException();
        }finally {
            if(rLock != null) {
                rLock.unlock();
            }
        }
    }

    public TicketPollRecord getByPollId (String pollId) {
        Date[] dates = StatisticsDateUtil.getDateArray(SearchTypeEnum.TODAY);
        LambdaQueryWrapper<TicketPollRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketPollRecord::getPollId, pollId);
        queryWrapper.eq(TicketPollRecord::getUserId, UserContext.getCurrentId());
        queryWrapper.between(TicketPollRecord::getCreateTime, dates[0], dates[1]);
        queryWrapper.last("limit 1");
        return ticketPollRecordMapper.selectOne(queryWrapper);
    }
}
